﻿

namespace Tentacle.Downloader
{
    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading.Tasks;

    using static Tentacle.Utils.Hepler;
    using static Tentacle.Utils.TentacleProtocol;

    using TaskRunningState = System.Boolean;

    internal sealed class RemoteDiscorveryService : IDisposable
    {
        UdpClient   _broadcast;
        IPEndPoint  _any;
        Task        _broadcastService;
        Task        _broadcastSendService;
        TaskRunningState    _taskState;

        public RemoteDiscorveryService()
        {
            _broadcast = new UdpClient(0);
            _any = new IPEndPoint(IPAddress.Broadcast, 9616);
            _taskState = true;
            _broadcastService = Task.Factory.StartNew(BroadcastMainLoop);
            _broadcastSendService = Task.Factory.StartNew(BroadcastSendLoop);
        }

        public void Scan()
        {
                       
        }

        IPEndPoint GetIPEndPoint(string content)
        {
            var ips = content.Split(":");
            return new IPEndPoint(IPAddress.Parse(ips[0]), int.Parse(ips[1]));
        }

        async void BroadcastMainLoop()
        {
            while (_taskState) {
                await Task.Delay(1000);                
                var recv = await _broadcast.ReceiveAsync();
                var ip = GetIPEndPoint(GetString(recv.Buffer));
                Discovery?.Invoke(ip);
            }
        }

        async void BroadcastSendLoop()
        {
            while (_taskState) {
                await Task.Delay(1000);
                Send(Find, _any, _broadcast);
            }
        }

        //---------------------------------------------------------------------------------------------------
        //  所有的远程下载节点都必须开启UDP服务,绑定9616端口,由远程连接服务发现节点
        //---------------------------------------------------------------------------------------------------
        public event Action<IPEndPoint> Discovery;

        public void Dispose()
        {
            _taskState = false;
            _broadcast.Dispose();
            _broadcastSendService.Dispose();
            _broadcastService.Dispose();
        }
    }
}
